package edu.webtech.project.server;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import edu.webtech.project.client.FileService;
import edu.webtech.project.server.domain.FileData;
import edu.webtech.project.shared.FileDataDTO;

@SuppressWarnings("serial")
public class FileServiceImpl extends RemoteServiceServlet implements
		FileService {
	
	BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	
	@Override
	public List<FileDataDTO> getAllFiles() throws IllegalArgumentException {
		return FileData.toDTO(FileData.getAllFiles());
	}

	@Override
	public void uploadFilesInfo(String fileName, String semesterName,
			String courseName, String url) throws IllegalArgumentException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {

			FileData fileData = new FileData(fileName, semesterName,
					courseName, url);
			pm.makePersistent(fileData);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}

	}

	@Override
	public String getFileUploadURL() throws IllegalArgumentException {
		// Get the URL where the file can be uploaded.
		// Fix: Since at the moment the files are hosted on my laptop
		// Therefore the URL had to be modified as seen below
		// At GAE the url is not created as for the local PC
		return blobstoreService.createUploadUrl("/webtechproject/handleUpload").replace("Fahad-PC", "127.0.0.1");
	}
	
	
	// Simple download feature when the request to this service is initiated via
	// an Anchor or Hyperlink
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		BlobKey blobKey = new BlobKey(request.getParameter("blob-key"));
		blobstoreService.serve(blobKey, response);

	}

	@Override
	public List<FileDataDTO> searchFiles(String fileName, String semesterName,
			String courseName) throws IllegalArgumentException {		
		return FileData.toDTO(FileData.searchFiles(fileName, semesterName, courseName));
	}

}
